/**
 * 统一 app 下的 entity 文件
 */
import * as fs from 'fs'
import { dirname, join, relative } from 'path'

const OUTPUT_PATH = join(__dirname, '../src/modules/app/entities.ts')
const ENTITIES_PATH = dirname(OUTPUT_PATH) // 获取 entities.ts 文件的父目录路径

function scanEntities(dir: string, output: string, arr: string[]) {
  const files = fs.readdirSync(dir)

  for (const file of files) {
    const fullPath = join(dir, file)
    const stat = fs.statSync(fullPath)

    if (stat.isDirectory()) {
      // 递归继续扫描子文件夹
      scanEntities(fullPath, output, arr)
    }
    else if (file.endsWith('.entity.ts')) {
      // 匹配 entity 文件
      let rel = relative(dirname(output), fullPath)

      if (!rel.startsWith('.')) {
        rel = `./${rel}`
      }
      rel = rel.replace(/\\/g, '/')
      rel = rel.replace('.ts', '')

      arr.push(rel)
    }
  }
}

const entities: string[] = []

scanEntities(ENTITIES_PATH, OUTPUT_PATH, entities)

console.log(entities)

async function main() {
  const str: string = entities.map((entity: string): string => `export * from '${entity}'\n`).join('')

  // const template = fs.readFileSync('./templates/entity.ejs', 'utf-8');
  // const dtoFormattedStr = await prettierEslint({
  //   text: str,
  //   filePath: 'entities.ts',
  // });

  // 确保父目录存在
  fs.mkdirSync(dirname(OUTPUT_PATH), { recursive: true })
  fs.writeFileSync(OUTPUT_PATH, str)
}

main()
